﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.App;
using TimKen.BussLogic;
using TimKen.DataEntity;
using System.Data;

namespace TimKen.Web.Shop
{
    public partial class OrderSend :TimKen.App.WebPage
    {
        protected UserAccountManager userM = new UserAccountManager();
        protected CustomerManager customerM = new CustomerManager();
        LinkManManager LinkM = new LinkManManager();
        AddressManager addressM = new AddressManager();
        public List<TimKen.DataEntity.Address> BillDs;
        public List<TimKen.DataEntity.Address> ShipDs;
        public DataRowCollection drcLinkMan;
        protected void Page_Load(object sender, EventArgs e)
        {
            TimKen.DataEntity.UserAccount userA = userM.GetModel(CurrentUserName);
            //if (userA != null && userA.CustomerID.HasValue)
            //{
            //    TimKen.DataEntity.Customer customer = customerM.GetModel(userA.CustomerID.Value);
            //    if (TimKen.App.Tools.CheckFrozen(customer.Frozen, customer.FrozenFrom, customer.FrozenTo))
            //    {
            //        Response.Redirect("/ErrorAuthority.aspx", true);
            //    }
            //    else
            //    {
                    //LoadListInfo();
                    if (!IsPostBack)
                    {
                        if (CurrentUserName == null || CurrentUserName == "")
                        {
                            Alert("您必须登录！", "../Index.aspx");
                        }
                        BindTransType();
                        BindResources();
                    }
            //    }
            //}
        }

        protected void BindResources()
        {
            this.txtExpectDate.ToolTip = GetLangString("ExpectDateToolTip");
            if (LanguageID == 2)
            {
                this.Button1.ImageUrl = "/images/enBtn/btn_continue.jpg";
                this.ImageButton1.ImageUrl = "/images/enBtn/submitOrder.jpg";
            }
        }

        /// <summary>
        /// 绑定联系人,送货地址,帐单地址
        /// </summary>
        //protected void LoadListInfo()
        //{
        //    TimKen.DataEntity.Customer customer = customerM.GetModel(userM.GetModel(CurrentUserName).CustomerID.Value);
        //    System.Data.DataSet LinkDs = LinkM.GetListByCardCode(customer.CardCode);
        //    //add by chenxm
        //    drcLinkMan = LinkDs.Tables[0].Rows;
        //    BillDs = addressM.GetBillToAddress(customer.CardCode, LanguageID);
        //    ShipDs = addressM.GetShipToAddress(customer.CardCode, LanguageID);
        //}

        /// <summary>
        /// 绑定运输方式
        /// </summary>
        protected void BindTransType()
        {
            TimKen.BussLogic.TransTypeManager ttM = new TimKen.BussLogic.TransTypeManager();
            System.Data.DataSet transDS = ttM.GetList(LanguageWhereStr);
            ddlTransType.DataSource = transDS;
            ddlTransType.DataBind();
        }

        protected void Button1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("/Product/ProductList.aspx");
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
        OrderManager orderM = new OrderManager();
        TimKen.DataEntity.Order order = orderM.CheckedOrder(CurrentUserName);
        if (order == null)
        {
            Alert(orderM.ValidMessage);
        }
        else
        {
            TimKen.DataEntity.Customer customer = customerM.GetModel(userM.GetModel(CurrentUserName).CustomerID.Value);
            order.Creator = CurrentUserName;
            order.OrderType = TimKen.DataEntity.OrderType.Order;
            order.ShipType = int.Parse(ddlTransType.SelectedValue);
            if (order.ShipType != 1)
                order.ShipToCode = Request["shiptocode"];
            else
                order.ShipToCode = "0";
            string newaddresscode = string.Empty;
            if (order.ShipToCode != "0")
            {
                if (order.ShipToCode == "newaddress")
                {
                    newaddresscode = "newaddress" + DateTime.Now.ToString();
                    order.ShipToCode = newaddresscode;
                    order.ShipAddress = Request["address"];
                }
                else
                {
                    order.ShipAddress = addressM.GetAddressString(addressM.GetModel(order.ShipToCode, "S", customer.CardCode));
                }
            }
            order.BillToCode = Request["billtoCode"];
            order.BillAddress = addressM.GetAddressString(addressM.GetModel(order.BillToCode, "B", customer.CardCode));
            order.CntctCode = Request["cntctcode"];
            //判断联系人,送货地址,帐单地址不能为空
            if (order.CntctCode.Trim() == "")
            {
                Alert(GetLangString("x_LinkManNotAllowBlank"));
                return;
            }
            if (order.BillToCode.Trim() == "")
            {
                Alert(GetLangString("x_BillAddressNotAllowBlank"));
                return;
            }
            if (order.ShipToCode.Trim() == "" && order.ShipType != 1)
            {
                Alert(GetLangString("x_ShipAddressNotAllowBlank"));
                return;
            }
            //如果自提的话,期望交货日期不能够为空
            if (this.txtExpectDate.Text.Trim() == "")
            {
                Alert(GetLangString("x_ExpectDateNotAllowBlank"));
                return;
            }
            if (!TypeParse.IsValidDate(this.txtExpectDate.Text.Trim()))
            {
                Alert(GetLangString("x_ExpectDateNotValid"));
                return;
            }
            //任何订单都需要后台审核...by miaozy at   2009.9.7
            //
            //如果运输方式非自提,则要等待EC管理员后台审核.否则直接通过
            //if (order.ShipType != 1)
            //{
            //    //设置状态为Pass
            //    order.OrderStatus = OrderStatus.ForFirstBridgeSOFreightConfirm;
            //}

            order.OrderStatus = OrderStatus.ForFirstBridgeSOFreightConfirm;
            order.ExpectDate = Convert.ToDateTime(this.txtExpectDate.Text.Trim());
            order.ContractTerm = Tools.GetDefualtOrderTerm();
            if (order.ShipType == 1)
            {
                order.Freight = 0;
            }
            if (order.ShipToCode.Equals(newaddresscode))
            {
                //保存收货地址
                AddressManager am = new AddressManager();
                Address address = new Address();
                address.AddressCode = order.ShipToCode;
                address.AdresType = "S";
                address.Street = order.ShipAddress;
                address.LanguageID = LanguageID;
                address.CardCode = customer.CardCode;
                address.Block = "";
                address.Building = "";
                address.City = "";
                address.Country = "";
                address.County = "";
                address.State = "";
                address.ZipCode = "";
                am.Add(address);
            }
            string orderID = null;
            orderID = orderM.Add(order);
            Tools.SendOrderCreateEmail(orderID);
            try
            {
                Response.Redirect("/order/OrderInfos.aspx?OrderID=" + orderID, false);
            }
            catch (System.Threading.ThreadAbortException)
            {

            }
            catch (Exception ex)
            {
                if (ex.Message == "not enough Inventory\r\n1")
                {
                    Alert(GetLangString("NotEnoughInventory"));
                    return;
                }
                Clogs.LogError("提交订单出错", ex);
                Alert(GetLangString("Error"));
                throw ex;

            }

            }
        }
    }
}